package com.nettywork.communication;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.util.function.Consumer;

public class ChatServerHandler extends SimpleChannelInboundHandler<String> {

    private static ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
        Channel c = channelHandlerContext.channel();
        channels.forEach(new Consumer<Channel>() {
            @Override
            public void accept(Channel channel) {
                if (channel.equals(channelHandlerContext.channel())) {
                    channel.write("自己发送:" + s + "^");
                } else {
                    channel.write(c.remoteAddress() + ":" + s + "^");
                }
                channel.flush();
            }
        });
        System.out.println(s);
    }

    /**
     * 有客户端连接时调用
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        channels.writeAndFlush(channel.remoteAddress() + "连接成功" + "^");
        channels.add(channel);
        channels.flush();
        System.out.println(channel.remoteAddress()+"连接成功");
    }

    /**
     * 当客户端断开时调用
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().remoteAddress()+"断开连接");
    }
}
